package com.demo.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author wang
 */
@Slf4j
public class ResponseUtil {
  private ResponseUtil() {
  }

  /**
   * 响应json数据给前端
   *
   * @param response
   * @param obj
   */
  public static void sendJsonMessage(HttpServletResponse response, Object obj) {
    response.setContentType("application/json; charset=utf-8");
    try (PrintWriter writer = response.getWriter()) {
      writer.print(JSON.toJSON(obj));
      response.flushBuffer();
    } catch (IOException e) {
      log.warn("响应json数据给前端异常，e = {}", ExceptionUtils.getStackTrace(e));
    }
  }

  /**
   * 响应HTML数据给前端
   *
   * @param response
   * @param json
   */
  public static void sendHtmlMessage(HttpServletResponse response, JSON json) {
    response.setContentType("text/html; charset=utf-8");
    try (PrintWriter writer = response.getWriter()) {
      writer.write(json.toJSONString());
      writer.flush();
    } catch (IOException e) {
      log.warn("响应HTML数据给前端异常，e = {}", ExceptionUtils.getStackTrace(e));
    }
  }

}
